package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */

@Slf4j
@Service
//因为是操作多张表，所以在上边加上事务，方便到时候回滚
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService iSeckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    //定义代理对象,
    private IVoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static{
        SECKILL_SCRIPT =new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    //阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks=new ArrayBlockingQueue<>(1024*1024);
    //线程池 单线程处理
    private static final ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();

    //该队列需要在程序开始时就执行,进行订单的处理,类初始化时执行线程池
    @PostConstruct
    public void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable{
        String queueName="stream.orders";
        @Override
        public void run() {

            while (true) {
                try{
                    //1 获取消息队列里边的订单信息 XREADGROUP GROUP g1 c1 count 1 block 2000 stream.order >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //2 判断获取消息是否成功
                    if (list == null || list.isEmpty()) {
                        //获取失败,说明没有信息,执行下一次获取
                        continue;
                    }
                    // 3 解析消息中的订单信息
                     MapRecord<String, Object, Object> record= list.get(0);
                    Map<Object, Object> map= record.getValue();
                     VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(map, new VoucherOrder(), true);
                    // 4创建订单
                    handlerVoucherOrder(voucherOrder);
                    //5 去消息队列中确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                }catch (Exception e)
                {
                    log.error("处理发生异常",e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true) {
                try{
                    //1 获取pending-list中订单信息 XREADGROUP GROUP g1 c1 count 1  stream.order 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //2 判断获取消息是否成功
                    if (list == null || list.isEmpty()) {
                        //获取失败,pendig-list中没有异常,结束循环
                        break;
                    }
                    // 3 解析消息中的订单信息
                    MapRecord<String, Object, Object> record= list.get(0);
                    Map<Object, Object> map= record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(map, new VoucherOrder(), true);
                    // 4创建订单
                    handlerVoucherOrder(voucherOrder);
                    //5 去消息队列中确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                }catch (Exception e)
                {
                    log.error("处理发生异常",e);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                }
            }
        }

        //创建订单的逻辑
        private void handlerVoucherOrder(VoucherOrder voucherOrder) {

            //获取用户
            Long userId = voucherOrder.getUserId();
            //创建锁对象
            RLock lock = redissonClient.getLock("lock:order:" + userId);
            //获取锁
            boolean b = lock.tryLock();
            if (!b)
            {
                //获取锁失败
                log.error("不允许重复下单");
                return ;
            }
            try{
                proxy.createVoucherOrder(voucherOrder);
            }finally {
                lock.unlock();
            }

        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //创建订单id
        Long orderId = redisIdWorker.nextId("order");
        //执行脚本 这里是吧订单相关的信息放在消息队列中,对于这些信息的的处理放在另一个线程中
        Long execute = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),orderId.toString()
        );
        //判断结果是否为0
        int i = execute.intValue();
        if (i != 0)
        {
            return Result.fail(i==1?"库存不足":"不能重复下单");
        }
        //获取代理对象
        proxy= (IVoucherOrderService) AopContext.currentProxy();

        //返回订单id
        return Result.ok(orderId);
    }

    //使用jdk自带的阻塞队列来完成这个操作
    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //执行脚本
        Long execute = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        //判断结果是否为0
        int i = execute.intValue();
        if (i != 0)
        {
            return Result.fail(i==1?"库存不足":"不能重复下单");
        }
        //为0,有购买资格,将下单信息保存在阻塞队列
        VoucherOrder voucherOrder=new VoucherOrder();
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId );
        //加入阻塞队列
        proxy= (IVoucherOrderService) AopContext.currentProxy();
        orderTasks.add(voucherOrder);
        //获取代理对象

        //返回订单id
        return Result.ok(orderId);
    }*/

    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //1 查询优惠券
        SeckillVoucher voucher= iSeckillVoucherService.getById(voucherId);
        //2 判断秒杀是否开始
        LocalDateTime beginTime = voucher.getBeginTime();
        if(beginTime.isAfter(LocalDateTime.now())){
            return Result.fail("活动还没开始");
        }
        //3 判读秒杀是否已经结束
        LocalDateTime endTime = voucher.getEndTime();
        if(endTime.isBefore(LocalDateTime.now())){
            return Result.fail("活动已经结束");
        }
        //4 判断库存是否充足
        int stock = voucher.getStock();
        if(stock<1){
            return Result.fail("当前优惠券没有了");
        }

        Long id = UserHolder.getUser().getId();  //用户进来的时候先获取锁，事务提交之后再释放锁，这时候就可以确保事物成功了

        //创建锁对象  使用的lua脚本来实现的
        //SimpleLock simpleLock=new SimpleLock("order"+id,stringRedisTemplate);
        //添加锁名称
        RLock lock = redissonClient.getLock("lock:order"+id);
        //无参默认实现是错误直接返回,不会重复获取锁
        boolean b = lock.tryLock();
        if(!b)
        {
            //获取锁失败
            return Result.fail("很抱歉,一个用户只能购买一单");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        }finally {
            //手動釋放鎖
            lock.unlock();
        }

    }*/

    @Transactional
    public void createVoucherOrder(VoucherOrder v){
        Long voucherId = v.getVoucherId();
        //实现一人一单
        Long id = v.getId();
        //根据用户id盒优惠券id来查询数据库，看是否存在
        int count = query().eq("user_id", id).eq("voucher_id", voucherId).count();
        if(count>0)
        {
            log.error("用户已经购买过了");
            return;
        }
        // 5 扣减库存
        //添加乐观锁，当获得则数据时查询更新, 这个用来解决超卖问题
        boolean voucher_id = iSeckillVoucherService.update().setSql("stock=stock-1")
                .eq("voucher_id", voucherId)
                .gt("stock",0)  //where voucherId =voucher  and stock >0
                .update();
        if(!voucher_id)
        {
            log.error("库存不足");
            return ;
        }

        save(v);


    }
}
